package com.cqupt.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cqupt.common.JsonData;
import com.cqupt.common.Pagination;
import com.cqupt.common.Result;
import com.cqupt.common.WebLog;
import com.cqupt.pojo.Tbuser;
import com.cqupt.service.UserService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    @WebLog(value = "abc")
    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @WebLog(value = "test1 abc")
    @RequestMapping("/test1")
    @ResponseBody
    public String test1(String userid) {
        return "test1 aaaaa";
    }

    @RequestMapping("/test2")
    @ResponseBody
    public String test2(HttpSession session) {
        session.setAttribute("username","张三");
        return "test2 bbbbb";
    }

    @RequestMapping("/test3")
    public String test3(Model model) {
        List list = userService.queryList();
        model.addAttribute("list",list);
        return "test3";
    }

    @RequestMapping("/userList")
    public String userList() {
        return "userList";
    }

    @RequestMapping("/userListData")
    @ResponseBody
    public JsonData userListData(Pagination pagination) {
        JsonData jsonData = new JsonData();

        Page page = userService.queryPageList(pagination);
        jsonData.setData(page.getResult());
        jsonData.setCount(page.getTotal());
/*        jsonData.setCode(1);
        jsonData.setMsg("请求失败");*/

        return jsonData;
    }

    @RequestMapping(value = "/userEdit",method = RequestMethod.GET)
    public String userEdit() {
        return "userEdit";
    }

    @RequestMapping(value = "/userEdit",method = RequestMethod.POST)
    @ResponseBody
    public Result userEdit_submit(Tbuser tbuser) {
        Result result = new Result();



        System.out.println("userid:" + tbuser.getUserid());

        if(tbuser.getUserid()==null) {  // 添加用户
            tbuser.setUserpwd("123456");
            userService.insertUser(tbuser);
        } else {    // 编辑用户
            userService.updateUser(tbuser);
        }

        result.setCode(0);
        result.setMsg("");
        return result;
    }

    @RequestMapping(value = "/userDelete",method = RequestMethod.POST)
    @ResponseBody
    public Result userDelete(Integer userid) {
        Result result = new Result();

        if(userid==1) {
            result.setCode(1);
            result.setMsg("不允许删除admin");
        } else {
            userService.deleteUser(userid);

            result.setCode(0);
            result.setMsg("");
        }

        return result;
    }

    @RequestMapping("/userData")
    @ResponseBody
    public Tbuser userData(Integer userid) {
        return userService.queryUser(userid);
    }

    @RequestMapping("/test4")
    public String test4() {
        return "test4";
    }

    @RequestMapping(value = "/test4_submit",method = RequestMethod.POST)
    @ResponseBody
    public Result test4_submit(Tbuser user, HttpSession session) throws UnsupportedEncodingException {
        Result result = new Result();

        Tbuser tbuser = userService.queryUser(user);
        if(tbuser==null) {
            result.setCode(1);
            result.setMsg("用户名不存在");
        } else {
            if(tbuser.getUserpwd().equals(user.getUserpwd())) {
                session.setAttribute("user",tbuser);
                result.setCode(0);

                String TOKEN_SECRET = "aqwe"; // 密钥
                long EXPIRE_TIME = 24*60*60*1000; // 过期时间 1天
                Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
                Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 算法对象
                //设置头信息
                HashMap<String, Object> header = new HashMap<>();
                header.put("typ", "JWT"); // 加密类型是 JWT
                header.put("alg", "HS256"); // 算法是 HS256
                String token = JWT.create()
                        .withHeader(header) // JWT添加header
                        .withClaim("username", tbuser.getUsername()) // 声明loginName
                        .withExpiresAt(date) // 设置过期时间
                        .sign(algorithm); // 签名

                result.setMsg(token);
            } else {
                result.setCode(2);
                result.setMsg("用户名或密码输入有误");
            }
        }
        return result;
    }

    @RequestMapping("/test5")
    public String test5() {
        return "test5";
    }

    @RequestMapping("/test5_submit")
    @ResponseBody
    @CrossOrigin
    public Result test5_submit(HttpServletRequest request) {
        Result result = new Result();
        try {

            String TOKEN_SECRET = "aqwe"; // 密钥
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 算法对象
            JWTVerifier verifier = JWT.require(algorithm).build(); // JWT验证器

            String token = request.getHeader("Authorization");
            if(token.indexOf("Bearer ")==0) {
                token = token.replaceFirst("Bearer ","");
            }
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("header:" + jwt.getHeader()); // header
            System.out.println("payload:" + jwt.getPayload()); // payload
            System.out.println("singature:" + jwt.getSignature()); // singature
            System.out.println("token:" + jwt.getToken()); // token

            // header中的元素用getHeaderClaim()获取
            System.out.println("typ:" + jwt.getHeaderClaim("typ").asString()); // header中的typ
            System.out.println("alg:" + jwt.getHeaderClaim("alg").asString()); // header中的alg

            // payload中的元素有2种写法
            // getClaim("username")
            // getClaims().get("username")
            String username = jwt.getClaim("username").asString();
            System.out.println("username:" + username); // 用户名

            System.out.println(jwt.getExpiresAt()); // 失效时间(到期时间)

            result.setCode(0);
            result.setMsg(username);
        } catch (Exception e){
            result.setCode(1);
            result.setMsg("验证失败");
            e.printStackTrace();
        }
        return result;
    }
}
